package com.freedom.base.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Description: 统一异常处理器
 * <p>CreateTime: 2023-03-12 下午 1:03</p>
 * <p>Email: 2396598264@qq.com</p>
 *
 * @author Chb
 */

@Slf4j
@RestControllerAdvice
public class ExceptionController {

    /**
     * 处理未知异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    private Result<Object> handleException(Exception exception) {
        basicHandleException(exception);
        return Result.fail("未知错误");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    private Result<Object> handleDuplicateKeyException(Exception exception) {
        basicHandleException(exception);
        String errMsg = exception.getMessage();
        int beginIndex = errMsg.indexOf("'");
        int endIndex = errMsg.indexOf("'", beginIndex + 1);
        String duplicateText = errMsg.substring(beginIndex + 1, endIndex);
        return Result.fail(duplicateText + "已存在");
    }

    /**
     * 基础处理异常
     *
     * @param exception
     */
    private void basicHandleException(Exception exception) {
        log.error("服务出错了，错误类型：{}", exception.getClass().toString());
        exception.printStackTrace();
    }

}
